<template>
    <div class="container">
        <div class="search-bar">
            <el-autocomplete :trigger-on-focus="false" style="width: 200px;" clearable :hide-loading="true"
                class="search-input" v-model="searchKeyword" :fetch-suggestions="fetchSuggestions"
                placeholder="搜索姓名、邮箱或电话" @select="handleSelect">
                <template #default="{ item }">
                    <div class="custom-suggestion-item">
                        <span>{{ item.real_name }} - </span>
                        <span>{{ item.email }} - </span>
                        <span>{{ item.phone }}</span>
                    </div>
                </template>
            </el-autocomplete>
            <el-button type="primary" @click="resetFields" class="reset-button">重置</el-button>
            <el-button type="primary" @click="addPerson" class="add-button">新增人员</el-button>
        </div>

        <el-empty v-if="!filteredPersonList.length && !loading" description="暂无数据" style="width: 100%; height: 80%;">
        </el-empty>

        <el-table v-if="filteredPersonList.length" v-loading="loading" ref="tableRef" :data="filteredPersonList"
            class="person-table" style="width: 100%" @row-click="handleRowClick" :highlight-current-row="true"
            @current-change="handleCurrentChange">

            <el-table-column label="编号" width="80" prop="id" sortable align="center"></el-table-column>
            <el-table-column prop="real_name" label="姓名" align="center"></el-table-column>
            <el-table-column prop="phone" align="center" label="电话"></el-table-column>
            <el-table-column prop="email" align="center" show-overflow-tooltip label="邮箱"></el-table-column>
            <el-table-column sortable prop="created_at" label="创建时间">
                <template #default="scope">
                    {{ formatDate(scope.row.created_at) }}
                </template>
            </el-table-column>
            <el-table-column sortable prop="updated_at" label="修改时间">
                <template #default="scope">
                    {{ formatDate(scope.row.updated_at) }}
                </template>
            </el-table-column>

            <el-table-column fixed="right" align="center" label="操作" width="260">
                <template #default="scope">
                    <el-button @click.stop="handleShowPermission(scope.row)" type="success"
                        size="small">自定义权限</el-button>
                    <el-button type="primary" icon="Edit" @click.stop="editPerson(scope.row)"
                        size="small">编辑</el-button>
                    <el-button type="danger" icon="Delete" @click.stop="deletePerson(scope.row)"
                        size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-if="totalItems > 0" @current-change="handlePageChange" :current-page="currentPage"
            :page-size="pageSize" :hide-on-single-page="true" background :pager-count="5" layout="prev, pager, next"
            :total="totalItems" class="pagination">
        </el-pagination>
    </div>

    <el-dialog destroy-on-close :title="currentUser ? '编辑人员' : '新增人员'" v-model="dialogVisible">
        <UserDialog @fetchUser="getPersonList" :currentUser="currentUser">
        </UserDialog>
    </el-dialog>
</template>
<script setup>
import { ref, onMounted, watch, defineProps, defineEmits } from 'vue';
import { formatDate } from '@/utils/date';
import UserDialog from './UserDialog.vue';
import { deleteUserApi, getUserListApi } from '@/api/user';
import { debounce } from '@/utils/DebounceAndThrottle';
import { useCompanyStore } from '@/stores/company';
import { useRoute } from 'vue-router';
import { deleteRoleApi, getRoleApi } from '../../../../api/auth';
import { handleError } from '@/utils/handleError';

// 删除或注释掉这个props定义，因为我们不再需要它
// const props = defineProps({
//     company_id: {
//         type: [Number, String],
//         default: null,
//     },
// });

const emits = defineEmits(['showPermission']);
const loading = ref(false);
const filteredPersonList = ref([]);
const tableRef = ref();
const currentUser = ref(null);
const dialogVisible = ref(false);
const currentPage = ref(1);
const pageSize = ref(12);
const totalItems = ref(0);
const searchKeyword = ref('');
const currentRow = ref(null);

// 处理行点击
const handleRowClick = (row) => {
    currentRow.value = row;
    editPerson(row)
};

// 处理当前行变化
const handleCurrentChange = (currentRow) => {
    if (!currentRow) {
        emits('showPermission', null);
    }
};

// 处理显示权限
const handleShowPermission = (row) => {
    if (tableRef.value) {
        tableRef.value.setCurrentRow(row);
    }
    emits('showPermission', row);
};

// 清除当前选中行
const clearCurrentRow = () => {
    if (tableRef.value) {
        tableRef.value.setCurrentRow(null);
    }
};

// 获取人员列表
const getPersonList = async (offset = 0, limit = pageSize.value) => {
    dialogVisible.value = false;
    try {
        loading.value = true;
        const params = {
            offset,
            limit,
            real_name: searchKeyword.value ? `%${searchKeyword.value}%` : '%',
        };

        // 简化条件，直接使用companyStore.currentCompany.id
        params.company_id = companyStore.currentCompany.id;

        const res = await getUserListApi(params);
        if (res.code === 200) {
            const { results, total } = res;
            filteredPersonList.value = results;
            totalItems.value = total;

            // 如果当前有选中行，检查更新后是否还存在
            if (currentRow.value) {
                const stillExists = results.some(item => item.id === currentRow.value.id);
                if (!stillExists) {
                    clearCurrentRow();
                    emits('showPermission', null);
                }
            }
        } else {
            handleError(res, '获取用户信息失败，请稍后重试')
        }
    } catch (error) {
        handleError(error, '获取用户信息失败，请稍后重试')
    } finally {
        loading.value = false;
    }
};

// 重置所有过滤器
const resetFields = () => {
    searchKeyword.value = '';
    currentPage.value = 1;
    clearCurrentRow();
    emits('showPermission', null);
    getPersonList(0, pageSize.value);
};

const editPerson = (person) => {
    dialogVisible.value = true;
    currentUser.value = person;
};

const deletePerson = (person) => {
    ElMessageBox.confirm(
        `确认删除用户 ${person.real_name} 吗？`,
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        // 删除逻辑
        await fetchDeletePerson(person.username);
        getPersonList((currentPage.value - 1) * pageSize.value, pageSize.value);
    }).catch(() => {
        handleError(error, '删除用户失败，请稍后重试')
    });
};

async function fetchDeletePerson(username) {
    try {
        const Roles = await getRoleApi({
            username
        })

        for (let i = 0; i < Roles.data.length; i++) {
            const role = Roles.data[i]
            await deleteRoleApi({
                user_name: username,
                company_id: companyStore.currentCompany.id,
                role_name: role
            })
        }

        let res = await deleteUserApi({
            username,
        })
        if (res.code === 200) {
            ElMessage.success('删除成功');
        } else {
            handleError(res, '删除用户失败，请稍后重试')
        }
    } catch (error) {
        handleError(error, '删除用户失败，请稍后重试')
    }
}

const handleSelect = (item) => {
    searchKeyword.value = item.real_name;
    currentPage.value = 1;
    clearCurrentRow();
    getPersonList(0, pageSize.value);
};

const fetchSuggestions = debounce(async (query, cd) => {
    if (!query) {
        cd([]);
        return;
    }

    try {
        const params = {
            offset: 0,
            limit: 5,
            company_id: companyStore.currentCompany.id
        };

        const [realNamesRes, emailsRes, phonesRes] = await Promise.all([
            getUserListApi({
                ...params,
                real_name: '%' + query + '%',
            }),
            getUserListApi({
                ...params,
                email: '%' + query + '%',
            }),
            getUserListApi({
                ...params,
                phone: '%' + query + '%',
            }),
        ]);

        const results = [];
        [realNamesRes, emailsRes, phonesRes].forEach((item) => {
            if (item.code === 200) {
                results.push(...item.results);
            }
        });
        const uniqueArray = Array.from(new Map(results.map((item) => [item.id, item])).values());
        cd(uniqueArray);
    } catch (error) {
        handleError(error, '获取用户信息失败，请稍后重试')
        cd([]);
    }
}, 500);

const addPerson = () => {
    currentUser.value = null;
    dialogVisible.value = true;
};

const handlePageChange = (page) => {
    currentPage.value = page;
    clearCurrentRow();
    getPersonList((currentPage.value - 1) * pageSize.value, pageSize.value);
};
let companyStore = useCompanyStore();
watch(() => companyStore.currentCompany, () => {
    getPersonList(0, pageSize.value);
})

onMounted(() => {
    getPersonList(0, pageSize.value);
});

// 暴露给父组件的方法
defineExpose({
    clearCurrentRow,
});
</script>

<style scoped>
.search-bar {
    display: flex;
    align-items: center;
    padding: 0.6rem 1.1rem;
    border-radius: 8px;
    margin-bottom: 20px;
    gap: 1rem;
}

.container {
    width: 100%;
    height: 100%;
}

.pagination {
    margin-top: 1rem;
}

.person-table {
    /* 添加过渡效果 */
    transition: all 0.3s ease;
}

/* 可选：添加鼠标悬停效果 */
.person-table :deep(tbody tr:hover) {
    cursor: pointer;
    background-color: var(--el-table-row-hover-bg-color);
}
</style>